<?php
// This controller handles the logic for the my bids page

class MyBidsController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function actionSupplier()
	{
		if(Yii::app()->user->isGuest)
		{
			echo "Please Login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='b')
		{
			echo "you have no authority to view the supplier page";
		}
		else
		{
		/*	$bidrequestsDataProvider = new CActiveDataProvider('Auctions', array(
								'criteria'=>array(
										'condition'=>'sorgRackRelation.organization_ID='.Yii::app()->user->organizationID.' and orgProRelation.organization_ID='.Yii::app()->user->organizationID.' and status_ID='.AuctionStatus::$OPEN,
										'with'=>array('tank', 'product', 'site', 'product.orgProRelation', 'site.rack.orgRackRelation'),
									),
								'pagination'=>array(
										'pageSize'=>20,
									),
								'sort'=>array(
										'defaultOrder'=>'auction_end ASC',
									),
								)
							);*/
			//it's difficult to use an active data provider to fetch 
			//bid request records from database(maybe the defect of object relational mapping...)
			$sql = "SELECT * FROM `auctions` `auction` LEFT OUTER JOIN `tanks` `tank` ON (`auction`.`tank_ID`=`tank`.`tank_ID`)" .
					" LEFT OUTER JOIN `users` `user` ON(`auction`.`user_ID`=`user`.`user_ID`) LEFT OUTER JOIN `organizations` `organization`" .
					" ON (`organization`.`organization_ID`=`user`.`organization_ID`)" .
					" LEFT OUTER JOIN `products` `product` ON (`auction`.`product_ID`=`product`.`product_ID`) LEFT OUTER JOIN `organization_products` `orgProRelation`" .
					" ON (`orgProRelation`.`product_ID`=`product`.`product_ID`) LEFT OUTER JOIN `sites` `site` ON (`auction`.`site_ID`=`site`.`site_ID`) LEFT OUTER JOIN `racks` `rack`" .
					" ON (`site`.`home_rack_ID`=`rack`.`rack_ID`) LEFT OUTER JOIN `organization_racks` `orgRackRelation` ON (`orgRackRelation`.`rack_ID`=`rack`.`rack_ID`)" .
					" WHERE (orgRackRelation.organization_ID=".Yii::app()->user->organizationID." and orgProRelation.organization_ID=".Yii::app()->user->organizationID." and status_ID=1)";
			$sql2 = "SELECT count(*) FROM `auctions` `auction` LEFT OUTER JOIN `tanks` `tank` ON (`auction`.`tank_ID`=`tank`.`tank_ID`)" .
					" LEFT OUTER JOIN `products` `product` ON (`auction`.`product_ID`=`product`.`product_ID`) LEFT OUTER JOIN `organization_products` `orgProRelation`" .
					" ON (`orgProRelation`.`product_ID`=`product`.`product_ID`) LEFT OUTER JOIN `sites` `site` ON (`auction`.`site_ID`=`site`.`site_ID`) LEFT OUTER JOIN `racks` `rack`" .
					" ON (`site`.`home_rack_ID`=`rack`.`rack_ID`) LEFT OUTER JOIN `organization_racks` `orgRackRelation` ON (`orgRackRelation`.`rack_ID`=`rack`.`rack_ID`)" .
					" WHERE (orgRackRelation.organization_ID=".Yii::app()->user->organizationID." and orgProRelation.organization_ID=".Yii::app()->user->organizationID." and status_ID=1)";
			$count=Yii::app()->db->createCommand($sql2)->queryScalar();
			$bidrequestsDataProvider = new CSqlDataProvider($sql, array(						
								'keyField'=>'auction_ID',
								'totalItemCount'=>$count,
								'pagination'=>array(
										'pageSize'=>8,
									),
								'sort'=>array(
										'defaultOrder'=>'auction.auction_end ASC',
									),
								)
							);
			
			$activebidsDataProvider = new CActiveDataProvider('BidAuctions', array(
								'criteria'=>array(
										'condition'=>'t.user_ID='.Yii::app()->user->userID.' and status_ID='.AuctionStatus::$OPEN,
										'with'=>array('auction', 'auction.site', 'auction.tank', 'auction.product', 'auction.user.organization'),
									),
								'pagination'=>array(
										'pageSize'=>8,
									),
								'sort'=>array(
										'defaultOrder'=>'auction.auction_end ASC',
									),
								)
							);
			$openordersDataProvider = new CActiveDataProvider('Orders', array(
								'criteria'=>array(
										'condition'=>'t.user_ID='.Yii::app()->user->userID.' and t.status_ID='.AuctionStatus::$OPEN,
										'with'=>array('auction', 'auction.product', 'auction.user.organization', 'status'),
									),
								'pagination'=>array(
										'pageSize'=>8,
									),
								'sort'=>array(
										'defaultOrder'=>'auction.auction_end ASC',
									),
								)
							);
			$bidhistoryDataProvider = new CActiveDataProvider('Orders', array(
								'criteria'=>array(
										'condition'=>'t.user_ID='.Yii::app()->user->userID.' and t.status_ID='.AuctionStatus::$CLOSED,
										'with'=>array('auction', 'auction.product', 'auction.user.organization', 'status'),
									),
								'pagination'=>array(
										'pageSize'=>8,
									),
								'sort'=>array(
										'defaultOrder'=>'auction.auction_end ASC',
									),
								)
							);
			$operation=null;//determine which tab should be focus on
			if(isset($_GET['operation']))
			{
				$operation=$_GET['operation'];
			}
			$this->render('supplier', array('bidrequestsDataProvider'=>$bidrequestsDataProvider, 'activebidsDataProvider'=>$activebidsDataProvider, 'openordersDataProvider'=>$openordersDataProvider, 'bidhistoryDataProvider'=>$bidhistoryDataProvider, 'operation'=>$operation));
		}
	}
	
	/*
	 * called when submitting the prices in bidreponse page
	 */
	public function actionBidResponse() {
		
		if(Yii::app()->user->isGuest)
		{
			echo "Please Login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='b')
		{
			echo "you have no authority to view the supplier page";
		}
		else
		{
			$auction = Auctions::model()->with(array('product', 'user', 'tank', 'site', 'site.rack', 
						'site.sitetoolRelation.tool', 'tank.tankType', 'tank.tankPosition'))->findByPk($_GET['auction_ID']);
			$bidAuction = new BidAuctions;
			$bidAuction->scenario = 'create';
			if(isset($_POST['BidAuctions']))
			{
				
				$bidAuction->auction_ID = $auction->auction_ID;
				$bidAuction->user_ID = Yii::app()->user->userID;
				$bidAuction->attributes = $_POST['BidAuctions'];
				$bidAuction->delivered_price_per_gallon = $bidAuction->fuel_cost_per_gallon+
															$bidAuction->freight_cost_per_gallon+
															$bidAuction->ancillary_fees+
															$bidAuction->fed_excise_tax+
															$bidAuction->fed_lust+
															$bidAuction->fed_oil_spill_fee+
															$bidAuction->nc_road_tax+
															$bidAuction->nc_wholesale+
															$bidAuction->nc_inspection+
															$bidAuction->nc_tare;
				if($bidAuction->save())
				{
					$this->redirect(Yii::app()->request->baseUrl . '/myBids/supplier?operation=activebids');
				}
			}
			
			$this->render('bidresponse', array('auction'=>$auction, 'bidAuction'=>$bidAuction));
		}
	}
	
	/*
	 * ajax call to retrieve auction info to display by given an auction ID
	 */
	public function actionAuctionDetails()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$auction=Auctions::model()->with('tank', 'product', 'site')->findByPk($_GET['auction_ID']);
			//format the time
			$auction->auction_start=date("Y-m-d g:ia", strtotime($auction->auction_start));
			$auction->auction_end=date("Y-m-d g:ia", strtotime($auction->auction_end));
			$auction->delivery_due=date("Y-m-d g:ia", strtotime($auction->delivery_due));
			$auction->tank->inventory_last_time=date("Y-m-d g:ia", strtotime($auction->tank->inventory_last_time));
			
			echo CJSON::encode(array($auction, $auction->tank, $auction->product, $auction->site));
		}
	}
	/*
	 * ajax call to retrieve auction info to display by given an order ID
	 */
	public function actionOrderDetails()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$auction=Orders::model()->findByPk($_GET['order_ID'])->auction;
			//format the time
			$auction->auction_start=date("Y-m-d g:ia", strtotime($auction->auction_start));
			$auction->auction_end=date("Y-m-d g:ia", strtotime($auction->auction_end));
			$auction->delivery_due=date("Y-m-d g:ia", strtotime($auction->delivery_due));
			$auction->tank->inventory_last_time=date("Y-m-d g:ia", strtotime($auction->tank->inventory_last_time));
			
			echo CJSON::encode(array($auction, $auction->tank, $auction->product, $auction->site));
		}
	}
	
	public function actionCloseOrder()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$order = new Orders();
			$order->scenario='supplier-update';
			$order->order_ID=$_POST['order_ID'];
			$order->supplier_net_gallons=$_POST['net_gallons'];
			$order->supplier_gross_gallons=$_POST['gross_gallons'];
			if($order->validate())
			{
				//update supplier gallons and close time;
				Orders::model()->updateByPk($order->order_ID, array('supplier_net_gallons'=>$order->supplier_net_gallons, 'supplier_gross_gallons'=>$order->supplier_gross_gallons, 'supplier_close_time'=>date('Y-m-d H:i:s')) );
				//send supplier close order notification email
				try
				{
					$data = array();
					$data['auction_ID'] = Orders::model()->findByPk($_POST['order_ID'])->auction_ID;
					
					$email = new Email();
					$emailTOBUYER=Orders::model()->with('auction', 'auction.user')->findByPk($order->order_ID)->auction->user->emailAddress;
					$email->sendEmail($emailTOBUYER, 'EKOS-ADMIN', 'CLOSE ORDER NOTIFICATION', Email::$SUPPLIER_CLOSE, $data);
				}
				catch(Exception $e){}
				//update the order status to close if the supplier has closed it
				Orders::model()->updateByPk($order->order_ID, array('status_ID'=>AuctionStatus::$CLOSED)
					, 'buyer_close_time is not NULL and buyer_net_gallons='.$_POST['net_gallons'].' and buyer_gross_gallons='.$_POST['gross_gallons']);
				echo CJSON::encode('close-order-success');
			}
			else
				echo CJSON::encode($order->errors);
		}
	}
	
	/*
	 * validate if the user has placed a bid on that auction already
	 */
	public function actionValidateAuction()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$bidAuction=new BidAuctions;
			$bidAuction->auction_ID=$_POST['auction_ID'];
			$bidAuction->user_ID=Yii::app()->user->userID;
			$bidAuction->scenario='create';
			if($bidAuction->validate(array('auction_ID', 'user_ID')))
			{
				echo CJSON::encode(Yii::app()->request->baseUrl . '/myBids/bidresponse?auction_ID='.$bidAuction->auction_ID);
			}
			else
				echo CJSON::encode('#');
		}
	}
}
?>
